package juc.CAS;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * AtomicInteger的使用
 */
 class Account {
    private AtomicInteger balance;
    public Account(int balance){
        this.balance=new AtomicInteger(balance);
    }

    public int getBalance(){
        return  balance.get();
    }

    public void withDraw(Integer amount ){
        while (true){
        int pre = balance.get();
        int next = pre - amount;
        if(balance.compareAndSet(pre,next)){
            break;
        }
    }
}
}

public class CASDemo1{
    public static void main(String[] args) {
        Account account = new Account(10000);
        List<Thread> ts = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withDraw(10);
            }));
        }
        long start = System.nanoTime();
        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println(account.getBalance()
                + " cost: " + (end-start)/1000_000 + " ms");
    }
}
